
from encodings.punycode import T
from email.quoprimime import header_check
from typing import List
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit, join_room
from functools import wraps
import sys
import os
import asyncio
import time

# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, project_root)
print('project_root: ',project_root)

from src.backend.task_sever import TaskServer
from src.backend.data_bridge import DataBridge

class SocketServer:
    def __init__(self, app: Flask, socketio: SocketIO, 
                 task_server: TaskServer,
                 data_bridge: DataBridge
                 ):
        
        # 获取项目根目录
        self.project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

        
        # 设置模板和静态文件路径
        template_folder = os.path.join(self.project_root, 'web', 'templates')
        static_folder = os.path.join(self.project_root, 'web', 'static')

        print("template_folder:",template_folder)
        print("static_folder:",static_folder)


        # 初始化Flask应用
        self.app = app
        self.app.template_folder = template_folder
        self.app.static_folder = static_folder
        self.app.static_url_path = '/static'

        self.socketio = socketio
        self.task_server = task_server
        self.data_bridge = data_bridge
        self.register_routes()
        self.register_socketio_events()

        self.emit_progress = False

    def register_routes(self):
        @self.app.route('/')
        def index():
            return render_template('/index-file-mapper.html')

        
        # 添加调试页面路由
        @self.app.route('/debug')
        def debug():
            return render_template('/components-file-mapper/debug.html')

        
        @self.app.route('/debug/modify')
        def debug_modify():
            return render_template('/components-file-mapper/modify.html')

        
        @self.app.route('/debug/tree')
        def debug_tree():
            return render_template('/components-file-mapper/tree.html')
        
        @self.app.route('/debug/detail')
        def debug_detail():
            return render_template('/components-file-mapper/detail.html')
        
        @self.app.route('/vehicle-control-panel')
        def vehicle_control_panel():
            return render_template('/vehicle-control-panel.html')
        
        @self.app.route('/tasks-manager')
        def tasks_manager():
            return render_template('/tasks-manager.html')

    def get_client_ip(self):
        if request.headers.getlist("X-Forwarded-For"):
            return request.headers.getlist("X-Forwarded-For")[0]
        else:
            return request.remote_addr


    def register_socketio_events(self):
        @self.socketio.on('connect')
        def handle_connect():
            print('[Socket] 用户连接')
            emit('server_message', {'msg': '欢迎连接', 'ip': self.get_client_ip()})

        @self.socketio.on('chat_message')
        def handle_chat_message(data):
            msg = data.get('msg')
            print('[Socket] 收到消息:', msg)
            emit('chat_message', {'msg': msg}, broadcast=True)

        @self.socketio.on('join_room')
        def handle_join(data):
            room = data.get('room')
            join_room(room)
            emit('server_message', {'msg': f'你加入了房间 {room}'})
        
        @self.socketio.on('test_event')
        def handle_test_event(data):
            print('收到测试事件:', data)
            emit('test_event', {'reply': '测试事件收到了', 'original_data': data})

        @self.socketio.on('ping')
        def handle_ping(data):
            print('收到ping:', data)
            emit('pong', {'msg': 'pong', 'timestamp': data.get('timestamp')})

        @self.socketio.on('custom_event')
        def handle_custom_event(data):
            print('收到自定义事件:', data)
            emit('server_received', {'msg': '自定义事件处理完成', 'data': data})


        @self.socketio.on('command_event')
        def handle_command_event(data):
            print('收到命令事件:', data)
            emit('server_received', {'msg': '命令事件处理完成', 'data': data})

            results = asyncio.run(self.task_server.add_command_event(data))
            # print(f"=====================results================== \n{results}")
            fronted_json = self.data_bridge.parse_to_frontend(data,results)
            # print(f"=====================fronted_json================== \n{fronted_json}")

            emit('event_result', fronted_json)
        
        @self.socketio.on('login_remote')
        def handle_login_remote(data):
            print('收到登录事件:', data)
            emit('server_received', {'msg': '登录事件处理完成', 'data': data})
            success,msg = asyncio.run(self.task_server.login_remote(data))

            if success:
                emit('connection_result', {'success': True, 'msg': msg, 'data': data})
            else:
                emit('connection_result', {'success': False, 'msg': msg, 'data': data})

        @self.socketio.on('check_health')
        def handle_check_health(data):
            print('收到远程连接健康检查事件:', data)
            emit('server_received', {'msg': '健康检查事件处理完成', 'data': data})
            health_report = self.task_server.check_health()
            emit('server_message', {'msg': '健康检查事件处理完成', 'data': health_report})



        @self.socketio.on('load_config_list')
        def handle_load_config_list(data):
            print('收到加载配置列表事件:', data)
            emit('server_received', {'msg': '加载配置列表事件处理完成', 'data': data})
            config_list = self.task_server.load_config_list()
            # config_list = ['config1', 'config2', 'config3']

            emit('config_list', config_list)

        
        @self.socketio.on('save_config')
        def handle_save_config(data):
            print('收到保存配置事件:', data)
            emit('server_received', {'msg': '保存配置事件处理完成', 'data': data})
            success,msg = asyncio.run(self.task_server.save_config(data))
            emit('config_saved', {'success': True, 'msg': msg })

        @self.socketio.on('load_config')
        def handle_load_config(data):
            print('收到加载配置事件:', data)
            emit('server_received', {'msg': '加载配置事件处理完成', 'data': data})
            success,msg,config_data = self.task_server.load_config(data)
            emit('config_loaded', {'success': success, 'msg': '配置加载成功', 'msg': msg, 'data': config_data})

        @self.socketio.on('delete_config')
        def handle_delete_config(data):
            print('收到删除配置事件:', data)
            emit('server_received', {'msg': '删除配置事件处理完成', 'data': data})
            success,msg = self.task_server.delete_config(data)
            emit('config_deleted', {'success': success, 'msg': msg })

        @self.socketio.on('download_file')
        def handle_download_file_server(data):
            print('收到下载文件事件:', data)
            emit('server_received', {'msg': '下载文件事件处理完成', 'data': data})
            success,msg = self.task_server.download_file(data)
            self.socketio.emit('download_recall', {'success': success, 'msg': msg })

        
        @self.socketio.on('start_transfer')
        def handle_start_transfer(data):
            print('收到启动传输事件:', data)
            emit('server_received', {'msg': '启动传输事件处理完成', 'data': data})
            success,msg = self.task_server.start_transfer_scp(data)
            # emit('transfer_started', {'success': success, 'msg': msg })



        @self.socketio.on('stop_transfer')
        def handle_stop_transfer(data):
            print('收到停止传输事件:', data)
            emit('server_received', {'msg': '停止传输事件处理完成', 'data': data})
            success,msg = self.task_server.stop_transfer(data)
            emit('transfer_stopped', {'success': success, 'msg': msg })

        @self.socketio.on('get_progress_list')
        def handle_get_progress(data):
            print('收到获取进度事件:', data)
            emit('server_received', {'msg': '获取进度事件处理完成', 'data': data})
            # while True:
            #     progress = self.task_server.get_progress(data)
            #     emit('progress_list', progress)
            #     print(progress)
            #     socketio.sleep(1) 
            #     if progress==[] or progress[0]['is_transferring']==False:
            #         break
            # progress = self.task_server.get_progress(data)
            # emit('progress_list', progress)
            # 启动后台任务
            self.emit_progress = True
            self.socketio.start_background_task(target=self.progress_background_task, data=data)
        
        @self.socketio.on('stop_progress')
        def handle_stop_progress(data):
            print('收到停止发送进度事件:', data)
            emit('server_received', {'msg': '停止发送进度事件处理完成', 'data': data})
            self.emit_progress = False


    def progress_background_task(self,data):
        while True:
            progress = self.task_server.get_progress(data)
            socketio.emit('progress_list', progress)

            socketio.sleep(1)

            # if progress[0]['is_transferring'] == False:
            #     break

            
            if progress == []:
                break            
            
            if self.emit_progress==False:
                break


    # def download_file_progress(self,filename,size,sent,extra_params):
    #     socketio = extra_params['socketio']
        
    #     print(f'filename:{filename}, size:{size}, sent:{sent}')
    #     socketio.emit('download_progress', {'filename': filename, 'size': size, 'sent': sent})





if __name__ == '__main__':
    # ------------------------- 项目入口 -------------------------
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your-secret-key'
    socketio = SocketIO(app, cors_allowed_origins='*')
    task_server = TaskServer()
    data_bridge = DataBridge()


    asyncio.run(task_server.login_remote_preset())


    # 注册你的路由和事件模块
    my_server = SocketServer(app, socketio, task_server, data_bridge)


    socketio.run(app, host='0.0.0.0', port=7712, debug=True)